<?php


namespace App\Http\Controllers;

use App\Internals\BillingInternal;
use App\Models\Course;
use App\Models\Series;

class CourseController extends Controller
{
    /*
     * @api get /course-api/courses 课程列表
     * @version 0.0.1
     * @group web
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *     "items[项]":[{
     *       "id[id]":1,
     *       "name[名称]":"who we are?",
     *       "level[级别]":1,
     *       "description[描述]":"a lesson"}]
     *   }
     * }
     */
    public function index()
    {
        /** @var Series $seriesObj */
        $seriesObj = Series::find(1);
        $data = [
            'seriesName' => $seriesObj->getName(),
        ];
        $coursesObj = Course::hasPublished()->get();
        $courseIds = BillingInternal::getCourseIdsByUserId($this->userId);
        $items = [];
        /** @var Course $courseObj */
        foreach ($coursesObj as $courseObj) {
            $cover = $courseObj->cover()->value('uri');
            if ($cover) {
                $cover .= '?x-oss-process=style/course_cover';
            }
            $item = [
                'id' => $courseObj->getId(),
                'name' => $courseObj->getName(),
                'description' => $courseObj->getDescription(),
                'level' => $courseObj->getLevel(),
                'price' => $courseObj->getPrice(),
                'discountPrice' => $courseObj->getDiscountPrice(),
                'cover' => $cover,
                'actualPrice' => bcsub($courseObj->getPrice(), $courseObj->getDiscountPrice(), 2)

            ];
            $item['isBuy'] = (int)in_array($courseObj->getId(), $courseIds);
            $items[] = $item;
        }
        $data['courses'] = $items;
        return $this->sendSuccessJson($data);
    }


    /*
     * @api get /course-api/levels 课程列表
     * @version 0.0.1
     * @group web
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *     "items[项]":[{
     *       "id[id]":1,
     *       "name[名称]":"who we are?",
     *       "level[级别]":1,
     *       "description[描述]":"a lesson"}]
     *   }
     * }
     */
    public function levels()
    {
        /** @var Series $seriesObj */
        $seriesObj = Series::find(1);
        $data = [
            'seriesName' => $seriesObj->getName(),
        ];
        $coursesObj = Course::hasPublished()->get();
        $items = [];
        /** @var Course $courseObj */
        foreach ($coursesObj as $courseObj) {
            $items[] = [
                'id' => $courseObj->getId(),
                'name' => $courseObj->getName(),
                'level' => $courseObj->getLevel(),
                'price' => $courseObj->getPrice(),
                'actualPrice' => bcsub($courseObj->getPrice(), $courseObj->getDiscountPrice(), 2)

            ];
        }
        $data['courses'] = $items;
        return $this->sendSuccessJson($data);
    }
}
